package vn.com.vega.chacha.v2;

import java.util.HashMap;
import java.util.List;

import vn.com.vega.chacha.R;
import vn.com.vega.chacha.v2.player.PlayerService;
import vn.com.vega.music.database.DataStore;
import vn.com.vega.music.objects.Song;
import vn.com.vega.music.utils.AnimationChaCha;
import vn.com.vega.music.utils.Const;
import vn.com.vega.music.utils.Util;
import vn.com.vega.music.view.adapter.CurrentPlaylistAdapter;
import vn.com.vega.music.view.adapter.PlayerViewAdapter;
import vn.com.vega.music.view.custom.TopTaskbarView;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class PlayerScreen extends ActivityBase implements OnClickListener,
		OnSeekBarChangeListener {
	private static final int UPDATE_PROGRESS = 1;

	private ViewPager mViewPaper;
	private PlayerViewAdapter mPlayerViewAdapter;
	private ImageButton mBackBtn;
	private ImageButton mPlayPauseBtn;
	private ImageButton mNextBtn;
	private ImageButton mShufferRepeateBtn;
	private ImageButton mPlayListBtn;
	private SeekBar mSongProgress;
	private TextView mCurrentTime;
	private TextView mTotalTime;
	private TopTaskbarView mTopTaskView;

	private View mLayoutPlayList;
	private TextView mNumberSongInPlaylist;
	private ListView mListCurrentSongPlay;

	private HashMap<Song, String> songLyrics = new HashMap<Song, String>();

	private int mCurrentShufferIndex = 0;
	private int[] shufferRepeate = { R.drawable.ic_shuffer_off,
			R.drawable.ic_shuffer_on, R.drawable.ic_repeate_all,
			R.drawable.ic_repeate_one_song };

	public String getSongLyric(Song song) {
		return songLyrics.get(song);
	}

	public void setLyricForSong(Song song, String lyric) {
		if (songLyrics.size() > 20) {
			songLyrics.clear();
		}

		if (songLyrics.containsKey(song)) {
			songLyrics.remove(song);
		}
		songLyrics.put(song, lyric);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.player_screen);
		mViewPaper = (ViewPager) findViewById(R.id.paperview_player_screen);
		mPlayerViewAdapter = new PlayerViewAdapter(getSupportFragmentManager());
		mViewPaper.setAdapter(mPlayerViewAdapter);
		mViewPaper.setCurrentItem(PlayerViewAdapter.INDEX_THUMB_VIEW);
		mBackBtn = (ImageButton) findViewById(R.id.bt_previous);
		mPlayPauseBtn = (ImageButton) findViewById(R.id.bt_pause_play);
		mNextBtn = (ImageButton) findViewById(R.id.bt_next);
		mPlayListBtn = (ImageButton) findViewById(R.id.bt_playlist);
		mSongProgress = (SeekBar) findViewById(R.id.seekbar_song_progress);
		mCurrentTime = (TextView) findViewById(R.id.tv_current_time);
		mTotalTime = (TextView) findViewById(R.id.tv_total_time);
		mTopTaskView = (TopTaskbarView) findViewById(R.id.topTaskbarView_player_screen);
		mShufferRepeateBtn = (ImageButton) findViewById(R.id.bt_shuffer_repeat);
		mLayoutPlayList = findViewById(R.id.layout_background_playlist);
		mNumberSongInPlaylist = (TextView) findViewById(R.id.tv_playlist_title);
		mListCurrentSongPlay = (ListView) findViewById(R.id.lv_list_song_current_play);

		// mTopTaskView.changeToPlayerScreen();
		mTopTaskView.showBackButton();
		mBackBtn.setOnClickListener(this);
		mPlayPauseBtn.setOnClickListener(this);
		mNextBtn.setOnClickListener(this);
		mSongProgress.setOnSeekBarChangeListener(this);
		mShufferRepeateBtn.setOnClickListener(this);
		mPlayListBtn.setOnClickListener(this);
		mLayoutPlayList.setOnClickListener(this);

		intPlayerControlState();
		initPlayerMode();
	}
	
	private void initPlayerMode() {
		DataStore dataStore = DataStore.getInstance();
		int mRepeatMode, mShuffleMode;
		try {
			mRepeatMode 	= Integer.valueOf(dataStore.getConfig(Const.PLAYER_REPEATE_MODE)).intValue();
		} catch (Exception e) {
			// TODO: handle exception
			 mRepeatMode	= PlayerService.REPEAT_NONE;
		}
		try {
			mShuffleMode 	= Integer.valueOf(dataStore.getConfig(Const.PLAYER_SHUFFLE_MODE)).intValue();
		} catch (Exception e) {
			// TODO: handle exception
			mShuffleMode	= PlayerService.SHUFFLE_OFF;
		}
		if (mShuffleMode == PlayerService.SHUFFLE_ON) {
			mCurrentShufferIndex = 1;
		}
		if (mRepeatMode == PlayerService.REPEAT_ALL) {
			mCurrentShufferIndex = 2;
		}
		if (mRepeatMode == PlayerService.REPEAT_CURRENT) {
			mCurrentShufferIndex = 3;
		}
		mShufferRepeateBtn
		.setImageResource(shufferRepeate[mCurrentShufferIndex]);
	}

	private void intPlayerControlState() {
		int duration = Util.getTotalTime();
		mSongProgress.setMax(duration);
		int position = Util.getCurrentTime();
		mSongProgress.setProgress(position);
		mCurrentTime.setText(Util.intToStringTimeFormat(Util.getCurrentTime()));
		mTotalTime.setText(Util.intToStringTimeFormat(Util.getTotalTime()));
		if (Util.isPlaying()) {
			mPlayPauseBtn.setSelected(false);
		} else {
			mPlayPauseBtn.setSelected(true);
		}
		if (Util.isPlaying()) {
			handler.sendEmptyMessage(UPDATE_PROGRESS);
		} else {
			handler.removeCallbacksAndMessages(null);
		}
//		Song currentSong = Util.getCurrentSongPlay();
//		if (currentSong != null && currentSong.isLocalSong()) {
//			mViewPaper.setOnTouchListener(onTouchListener);
//		} else {
//			mViewPaper.setOnClickListener(null);
//		}
	}
	
//	View.OnTouchListener onTouchListener= new View.OnTouchListener() {
//		
//		@Override
//		public boolean onTouch(View v, MotionEvent event) {
//			// TODO Auto-generated method stub
//			
//			// Disable ontouch
//			return true;
//		}
//	};

	private void UpdateInfo() {
		// TODO: update info in fragment
		intPlayerControlState();
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_PROGRESS:
				removeMessages(UPDATE_PROGRESS);
				updateProgress();
				sendEmptyMessageDelayed(UPDATE_PROGRESS, 1000);
				break;

			default:
				break;
			}
		}
	};

	private void updateProgress() {
		mCurrentTime.setText(Util.intToStringTimeFormat(Util.getCurrentTime()));
		mSongProgress.setProgress(Util.getCurrentTime());
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (PlayerService.PLAYSTATE_CHANGED.equalsIgnoreCase(action)) {
				UpdateInfo();
//				if (Util.isPlaying()) {
//					handler.sendEmptyMessage(UPDATE_PROGRESS);
//					// PlayerViewThumbFrament thumbFrament =
//					// (PlayerViewThumbFrament)
//					// mPlayerViewAdapter.getItem(PlayerViewAdapter.INDEX_THUMB_VIEW);
//					// if (thumbFrament != null) {
//					// thumbFrament.updateInfo();
//					// }
//				} else {
//					handler.removeMessages(UPDATE_PROGRESS);
//				}
			}
		}
	};

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		handler.removeCallbacksAndMessages(null);
		super.onDestroy();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.bt_previous:
			Util.back();
			break;
		case R.id.bt_pause_play:
			if (Util.isPlaying()) {
				Util.pause();
				mPlayPauseBtn.setSelected(true);
			} else {
				Util.play();
				mPlayPauseBtn.setSelected(false);
			}
			break;
		case R.id.bt_next:
			Util.next();
			break;
		case R.id.bt_shuffer_repeat:
			if (mCurrentShufferIndex == shufferRepeate.length - 1) {
				mCurrentShufferIndex = 0;
			} else {
				mCurrentShufferIndex += 1;
			}
			mShufferRepeateBtn
					.setImageResource(shufferRepeate[mCurrentShufferIndex]);
			switch (mCurrentShufferIndex) {
			case 0:
				Util.setShuffleMode(PlayerService.SHUFFLE_OFF);
				Util.setRepeateMode(PlayerService.REPEAT_NONE);
				break;
			case 1:
				Util.setShuffleMode(PlayerService.SHUFFLE_ON);
				Util.setRepeateMode(PlayerService.REPEAT_NONE);
				break;
			case 2:
				Util.setShuffleMode(PlayerService.SHUFFLE_OFF);
				Util.setRepeateMode(PlayerService.REPEAT_ALL);
				break;
			case 3:
				Util.setShuffleMode(PlayerService.SHUFFLE_OFF);
				Util.setRepeateMode(PlayerService.REPEAT_CURRENT);
				break;
			default:
				break;
			}
			break;
		case R.id.layout_background_playlist:
			hidePlaylist();
			break;
		case R.id.bt_playlist:
			showPlaylist();
			break;
		default:
			break;
		}
	}

	private void showPlaylist() {
		if (!mLayoutPlayList.isShown()) {
			mLayoutPlayList.setVisibility(View.VISIBLE);
			List<Song> listSongPlay = Util.getListSongPlay();
			if (listSongPlay != null && listSongPlay.size() > 0) {
				int indextCurrentSong = Util.getIndexCurrentSongPlay();
				CurrentPlaylistAdapter apdapter = new CurrentPlaylistAdapter(
						listSongPlay, indextCurrentSong, this);
				mListCurrentSongPlay.setAdapter(apdapter);
				mNumberSongInPlaylist.setText(String.format(
						getString(R.string.current_playlist_title),
						listSongPlay.size()));
				mLayoutPlayList.startAnimation(AnimationChaCha
						.inFromRightAnimation(200));
				mLayoutPlayList.setVisibility(View.VISIBLE);
				mListCurrentSongPlay
						.setOnItemClickListener(new AdapterView.OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								// TODO Auto-generated method stub
								hidePlaylist();
								Util.openSongAtPosition(arg2);
							}
						});
			}
		}
	}

	private void hidePlaylist() {
		if (mLayoutPlayList.isShown()) {
			mLayoutPlayList.startAnimation(AnimationChaCha
					.outToRightAnimation(200));
			mLayoutPlayList.setVisibility(View.GONE);
		}
	}

	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub
		if (fromUser) {
			Util.seek(progress);
		}
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		unregisterReceiver(receiver);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		IntentFilter inten = new IntentFilter();
		inten.addAction(PlayerService.PLAYSTATE_CHANGED);
		inten.addAction(PlayerService.SONG_END);
		inten.addAction(PlayerService.SONG_ERROR);
		registerReceiver(receiver, inten);
	}

}
